<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="theme-color" content="#000000"/>
    <style>
        #root {
            margin: 50px;
        }

        div {
            padding: 10px;
        }
    </style>
</head>
<body>
<div id="root"></div>

<script>
    let root = document.getElementById('root');

    window.onpushstate = function (state, title, url) {
        root.innerHTML = url;
    };
    //点击浏览器回退会触发onpopstate事件:event= PopStateEvent事件，

    //现在要做的是无论路径怎么改变都要触发onpushstate事件，通过事件来拿到最近的路径，然后赋给root
    !(function (history) {
        let pushState = history.pushState;  //在自执行函数中缓存旧的pushState方法
        history.pushState = function (state, title, url) {
            if (typeof window.onpushstate === 'function') {
                window.onpushstate(state, title, url)
            }
            pushState.call(history, state, title, url);

        }
    })(window.history);


    window.onpopstate = function (event) {
        console.log({type: event.type, state: event.state, pathname: window.location.pathname})
        root.innerHTML = window.location.pathname;
    };

    //pushState是不会触发事件的
    setTimeout(() => {
        window.history.pushState({page: 1}, 'page1', '/page1')
    }, 1000)

    setTimeout(() => {
        window.history.pushState({page: 2}, 'page2', '/page2')
    }, 2000)

    setTimeout(() => {
        window.history.pushState({page: 3}, 'page3', '/page3')
    }, 3000)

    setTimeout(() => {
        window.history.go(-1)
    }, 4000)

</script>
</body>
</html>


